﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using NET6.WebAPI.Attributes;
using NET6.WebAPI.Dtos.Tool;
using NET6.WebAPI.Enums;
using NET6.WebAPI.Extensions;

namespace NET6.WebAPI.Filters
{
    /// <summary>
    /// 全局异常过滤器
    /// </summary>
    public class GlobalExceptionFilter : IExceptionFilter
    {
        public void OnException(ExceptionContext context)
        {
            var val = context.Exception.GetType()
                .GetAttributeValue<ExceptionResponseAttribute, ExceptionResponseCode>(attr => attr.Value);

            var res = new HttpResponseDto(val);

            if (val == ExceptionResponseCode.Unknown)
            {
                res.Result = new 
                {
                    context.Exception.Message,
                    context.Exception.StackTrace
                };
            }
            else if(val == ExceptionResponseCode.RequestFail)
            {
                res.Result = new
                {
                    Message = "请求地址：" + context.Exception.Message,
                };
            }
            
            context.Result = new ObjectResult(res);
        }
    }
}
